import traceback
from crawlers.utils import fetch_json_data
from crawlers.constants import DOUYIN_BASE_URL, DOUYIN_HOT_SEARCH_API
label_map = {0: "", 1: "新", 3: "热", 8: "独家", 9: "", 16: "辟谣"}


def _process_douyin_label(label:int):
    """处理抖音热搜中的标签，将标签转换为对应的中文描述

    Parameters:
        tag: 要处理的标签

    Returns:
        处理后的标签
    """
    if label in label_map:
        return label_map[label]
    else:
        return ""

def get_hot_search_from_douyin():
    """从抖音获取热搜数据

    Returns:
        热搜数据列表，每个热搜包含序号、标题、链接和热度、标签和图片链接信息
    """
    try:
        json_data = fetch_json_data(DOUYIN_HOT_SEARCH_API)
        hot_searches = []

        for item in json_data:
            hot_search_info = {}
            hot_search_info["order"] = item["position"]
            hot_search_info["title"] = item["word"]
            hot_search_info["url"] = f"{DOUYIN_BASE_URL}/hot/{item['sentence_id']}"
            hot_search_info["hot"] = item["hot_value"]
            hot_search_info["label"] = _process_douyin_label(item["label"])
            hot_search_info["photo_url"] = item["word_cover"]["url_list"][0] if item["word_cover"]["url_list"] else ""
            hot_searches.append(hot_search_info)

        return hot_searches
    except Exception as e:
        print("抖音热搜数据获取失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise